﻿using System;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using VNPT;
using VNPT.Utility;
using DevExpress.XtraGrid.Columns;
using DevExpress.Utils;
using VNPT.Utility.Profile;
using DevExpress.XtraEditors;
using VNPT.Data;

namespace VNPT.DoiSoat
{

    public partial class uDauCuoi : Core.uBase
    {
        private CellColorHelper _CellColorHelper_TanLoi;
        private CellColorHelper _CellColorHelper_BMT;
        public uDauCuoi()
        {
            InitializeComponent();
            _CellColorHelper_TanLoi = new CellColorHelper(myGridView_TanLoi);
            _CellColorHelper_BMT = new CellColorHelper(myGridView_BMT);

            this.myGridView_BMT.RowCellClick += (a, e) =>
            {
                if (e.Clicks == 2 && e.RowHandle >= 0)
                {
                    var file = myGridView_BMT.GetRowCellValue(e.RowHandle, "file").ToString();
                    if (File.Exists(file))
                    {
                        System.Diagnostics.Process.Start(file);
                    }
                }
            };

            this.myGridView_TanLoi.RowCellClick += (a, e) =>
            {
                if (e.Clicks == 2 && e.RowHandle >= 0)
                {
                    var file = myGridView_TanLoi.GetRowCellValue(e.RowHandle, "file").ToString();
                    if (File.Exists(file))
                    {
                        System.Diagnostics.Process.Start(file);
                    }
                }
            };
        }


        public override void LoadSetting()
        {
            Load();
            base.LoadSetting();
        }
        public override void SaveSetting()
        {
            Save();
            base.SaveSetting();
        }
        Xml xml = new Xml();


        public void Save()
        {
            DoiSoatSetting.Folder_TANLOI = btnThuMucBMT.Path;
            DoiSoatSetting.Folder_BMT = btnThuMucTanLoi.Path;
        }
        public void Load()
        {
            btnThuMucBMT.EditValue = DoiSoatSetting.Folder_TANLOI;
            btnThuMucTanLoi.EditValue = DoiSoatSetting.Folder_BMT;
        }


        private void btnKiemTra_Click(object sender, EventArgs e)
        {
            var daucuoi = (bool)radioGroup1.EditValue;
           // MessageBox.Show(daucuoi.ToString());
            string SourceStr1 = string.Format(@"Provider=vfpoledb;Data Source={0};", DoiSoatSetting.Folder_BMT);
            myGridControl_TanLoi.DataSource = TachDauVaCuoiFile(SourceStr1, DoiSoatSetting.Folder_BMT, daucuoi);
            KiemTraSaiLechTanLoi();

            string SourceStr2 = string.Format(@"Provider=vfpoledb;Data Source={0};", DoiSoatSetting.Folder_TANLOI);
            myGridControl_810.DataSource = TachDauVaCuoiFile(SourceStr2, DoiSoatSetting.Folder_TANLOI, daucuoi);
            KiemTraSaiLechBMT();

            foreach (GridColumn column in myGridView_TanLoi.Columns)
                column.OptionsColumn.AllowSort = DefaultBoolean.False;

            foreach (GridColumn column in myGridView_BMT.Columns)
                column.OptionsColumn.AllowSort = DefaultBoolean.False;

            KiemtraThieuCuocBMT();
            KiemtrathieuCuocTanLoi();
        }


        private DataTable TachDauVaCuoiFile(string cnstr, string path, bool DauCuoi)
        {
            var files = Directory.GetFiles(path).OrderBy(p => p).Where(p => p.ToUpper().EndsWith(".DBF"));
            if (files.Any())
            {
                using (var t = new DevExpress.Utils.WaitDialogForm("Vui lòng chờ..."))
                {
                    DbNetData Db = new DbNetData(cnstr, DataProvider.OleDb);
                    Db.Open();
                    DataTable dt = new DataTable();
                    foreach (var item in files)
                    {
                        t.SetCaption(string.Format("Đang đọc {0}...", Path.GetFileName(item)));
                        var strSQL = "";
                        if (DauCuoi)
                        {
                            strSQL = string.Format("SELECT '{0}' as File, * FROM '{0}' WHERE RECNO() =1 OR RECNO()= RECCOUNT()", item);
                        }
                        else
                        {
                            strSQL = string.Format(@"Select '{0}' As  File, * from (SELECT * from '{0}' WHERE MONTH(ngaybd) <> 0  ORDER BY ngaybd,giobd)a where RECNO() =1 OR RECNO()= RECCOUNT()", item);
                        }
                        
                        QueryCommandConfig Query = new QueryCommandConfig(strSQL);
                        dt.Merge(Db.GetDataSet(Query).Tables[0]);
                    }
                    Db.Close();
                    return dt;
                }
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(string.Format("Thư mục chọn [{0}] không phù hợp. Vui lòng kiểm tra lại!", path), "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }

        private void KiemTraSaiLechTanLoi()
        {
            int i = 0;
            var dem = 0;
            for (int j = 0; j < myGridView_TanLoi.RowCount - 1; j++)
            {
                if ((j % 2 == 0) && (i % 2 == 1))
                {
                    var t = 1;
                    try
                    {
                        var ngay = myGridView_TanLoi.GetRowCellValue(j, "ngaybd") ?? "";
                        var gio = myGridView_TanLoi.GetRowCellValue(j, "giobd") ?? "";
                        var k = string.Format("{0} {1}", ((DateTime)ngay).ToString("dd/MM/yyyy"), gio).ToDateTime();

                        var ngay2 = myGridView_TanLoi.GetRowCellValue(i, "ngaybd") ?? "";
                        var gio2 = myGridView_TanLoi.GetRowCellValue(i, "giobd") ?? "";
                        var k2 = string.Format("{0} {1}", ((DateTime)ngay2).ToString("dd/MM/yyyy"), gio2).ToDateTime();
                        if ((k - k2).TotalMinutes >= (int)spinPhut.Value)
                        {
                            _CellColorHelper_TanLoi.SetCellColor(j, myGridView_TanLoi.Columns[4], Color.Red);
                            _CellColorHelper_TanLoi.SetCellColor(j, myGridView_TanLoi.Columns[3], Color.Red);
                            _CellColorHelper_TanLoi.SetCellColor(j, myGridView_TanLoi.Columns[2], Color.Red);
                            _CellColorHelper_TanLoi.SetCellColor(j, myGridView_TanLoi.Columns[1], Color.Red);
                            _CellColorHelper_TanLoi.SetCellColor(j, myGridView_TanLoi.Columns[0], Color.Red);
                            dem++;
                        }
                        else
                        {
                            _CellColorHelper_TanLoi.SetCellColor(j, myGridView_TanLoi.Columns[4], Color.White);
                            _CellColorHelper_TanLoi.SetCellColor(j, myGridView_TanLoi.Columns[3], Color.White);
                            _CellColorHelper_TanLoi.SetCellColor(j, myGridView_TanLoi.Columns[2], Color.White);
                            _CellColorHelper_TanLoi.SetCellColor(j, myGridView_TanLoi.Columns[1], Color.White);
                            _CellColorHelper_TanLoi.SetCellColor(j, myGridView_TanLoi.Columns[0], Color.White);
                        }
                    }
                    catch (Exception)
                    {
                        _CellColorHelper_TanLoi.SetCellColor(j, myGridView_TanLoi.Columns[4], Color.Yellow);
                        _CellColorHelper_TanLoi.SetCellColor(j, myGridView_TanLoi.Columns[3], Color.Yellow);
                        _CellColorHelper_TanLoi.SetCellColor(j, myGridView_TanLoi.Columns[2], Color.Yellow);
                        _CellColorHelper_TanLoi.SetCellColor(j, myGridView_TanLoi.Columns[1], Color.Yellow);
                        _CellColorHelper_TanLoi.SetCellColor(j, myGridView_TanLoi.Columns[0], Color.Yellow);
                    }
                }
                i = j;
            }
            lblTanLoi.Text = string.Format("Host TÂN LỢI tìm thấy {0} trường hợp", dem);

            
        }


        private void KiemTraSaiLechBMT()
        {
            int i = 0;
            var dem = 0;
            for (int j = 0; j < myGridView_BMT.RowCount - 1; j++)
            {
                if ((j % 2 == 0) && (i % 2 == 1))
                {
                    var t = 1;
                    try
                    {
                        var ngay = myGridView_BMT.GetRowCellValue(j, "ngaybd") ?? "";
                        var gio = myGridView_BMT.GetRowCellValue(j, "giobd") ?? "";
                        var k = string.Format("{0} {1}", ((DateTime)ngay).ToString("dd/MM/yyyy"), gio).ToDateTime();

                        var ngay2 = myGridView_BMT.GetRowCellValue(i, "ngaybd") ?? "";
                        var gio2 = myGridView_BMT.GetRowCellValue(i, "giobd") ?? "";
                        var k2 = string.Format("{0} {1}", ((DateTime)ngay2).ToString("dd/MM/yyyy"), gio2).ToDateTime();
                        if ((k - k2).TotalMinutes >= (int)spinPhut.Value)
                        {
                            _CellColorHelper_BMT.SetCellColor(Convert.ToInt32(j), myGridView_BMT.Columns[Convert.ToInt32(4)], Color.Red);
                            _CellColorHelper_BMT.SetCellColor(Convert.ToInt32(j), myGridView_BMT.Columns[Convert.ToInt32(3)], Color.Red);
                            dem++;
                        }
                        else
                        {
                            _CellColorHelper_BMT.SetCellColor(Convert.ToInt32(j), myGridView_BMT.Columns[Convert.ToInt32(4)], Color.White);
                            _CellColorHelper_BMT.SetCellColor(Convert.ToInt32(j), myGridView_BMT.Columns[Convert.ToInt32(3)], Color.White);
                        }
                    }
                    catch (Exception)
                    {
                        _CellColorHelper_BMT.SetCellColor(Convert.ToInt32(j), myGridView_BMT.Columns[Convert.ToInt32(4)], Color.Yellow);
                        _CellColorHelper_BMT.SetCellColor(Convert.ToInt32(j), myGridView_BMT.Columns[Convert.ToInt32(3)], Color.Yellow);
                    }
                }
                i = j;
            }
            lblLoiBMT.Text = string.Format("Host BMT tìm thấy {0} trường hợp", dem);
            //myGridView_BMT.RowCount - 1
            
        }

        void KiemtraThieuCuocBMT()
        {
            try
            {
                var ngaycuoi = myGridView_BMT.GetRowCellValue(myGridView_BMT.RowCount - 1, "ngaybd") ?? "";
                var giocuoi = myGridView_BMT.GetRowCellValue(myGridView_BMT.RowCount - 1, "giobd") ?? "";
                var kcuoi = string.Format("{0} {1}", ((DateTime)ngaycuoi).ToString("dd/MM/yyyy"), giocuoi).ToDateTime();


                var ngaydau = myGridView_BMT.GetRowCellValue(0, "ngaybd") ?? "";
                var giodau = myGridView_BMT.GetRowCellValue(0, "giobd") ?? "";
                var kdau = string.Format("{0} {1}", ((DateTime)ngaydau).ToString("dd/MM/yyyy"), giodau).ToDateTime();



                var dauthang = new DateTime(DoiSoatSetting.NAM, DoiSoatSetting.THANG, 1, 0, 0, 0);
                var cuoithang = dauthang.AddMonths(1).AddDays(-1).AddHours(23).AddMinutes(59).AddSeconds(59);

                if (dauthang < kdau)
                {
                    XtraMessageBox.Show("Có thể thiếu cước đầu tháng của host 810, vui lòng kiểm tra lại!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }

                if (kcuoi < cuoithang)
                {
                    XtraMessageBox.Show("Có thể thiếu cước cuối tháng của host 810, vui lòng kiểm tra lại!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (Exception)
            {
            }
        }

        void KiemtrathieuCuocTanLoi()
        {
            try
            {
                var ngaycuoi = myGridView_TanLoi.GetRowCellValue(myGridView_TanLoi.RowCount - 1, "ngaybd") ?? "";
                var giocuoi = myGridView_TanLoi.GetRowCellValue(myGridView_TanLoi.RowCount - 1, "giobd") ?? "";
                var kcuoi = string.Format("{0} {1}", ((DateTime)ngaycuoi).ToString("dd/MM/yyyy"), giocuoi).ToDateTime();


                var ngaydau = myGridView_TanLoi.GetRowCellValue(0, "ngaybd") ?? "";
                var giodau = myGridView_TanLoi.GetRowCellValue(0, "giobd") ?? "";
                var kdau = string.Format("{0} {1}", ((DateTime)ngaydau).ToString("dd/MM/yyyy"), giodau).ToDateTime();



                var dauthang = new DateTime(DoiSoatSetting.NAM, DoiSoatSetting.THANG, 1, 0, 0, 0);
                var cuoithang = dauthang.AddMonths(1).AddDays(-1).AddHours(23).AddMinutes(59).AddSeconds(59);

                if (dauthang < kdau)
                {
                    XtraMessageBox.Show("Có thể thiếu cước đầu tháng của host 810, vui lòng kiểm tra lại!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }

                if (kcuoi < cuoithang)
                {
                    XtraMessageBox.Show("Có thể thiếu cước cuối tháng của host TÂN LỢI, vui lòng kiểm tra lại!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (Exception)
            {
            }
        }

        private void spinPhut_EditValueChanged(object sender, EventArgs e)
        {
            KiemTraSaiLechBMT();
            KiemTraSaiLechTanLoi();
            KiemtraThieuCuocBMT();
            KiemtrathieuCuocTanLoi();
        }

      

    }
}